<template>
  <div class="app-main-container">
    <div class="main_title mb10">短信统计</div>
    <div class="placeholder9 mb20">
      说明：本页面只统计平台短信数据，不包括阿里云短信数据。
    </div>
    <div class="df">
      <div class="top_left">
        <div class="header">
          <div class="df"><div class="title_before" /><strong>平台短信使用情况</strong></div>
          <el-button type="primary" @click="openRecharge">充值</el-button>
        </div>
        <el-progress
          class="progress"
          type="circle"
          :stroke-width="12"
          :width="160"
          :show-text="false"
          :percentage="useCase.percentage"
        />
        <div class="progress_wrap">
          <div>
            <strong style="font-size: 24px;" class="placeholder">{{ useCase.percentage }}%</strong>
          </div>
          <div class="placeholder9 mt10">剩余占比</div>
        </div>
        <div class="text_wrap">
          <div class="item">
            <div class="mb10 fs_18">{{ useCase.sum }}</div>
            <div class="fs12">累计充值(条)</div>
          </div>
          <div class="item">
            <div class="mb10 fs_18">{{ useCase.balance }}</div>
            <div class="fs12">未使用(条)</div>
          </div>
          <div class="item">
            <div class="mb10 fs_18">{{ useCase.used }}</div>
            <div class="fs12">已使用(条)</div>
          </div>
        </div>
      </div>
      <div class="separate" />
      <div class="top_right">
        <div class="mb20 df_sb">
          <strong class="df"><div class="title_before" />商户短信预警统计</strong>
          <el-select v-model="param.percent" clearable @change="initStaticWarning">
            <el-option
              v-for="item in warningOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </div>
        <div ref="SMSTypeRef" style="width: 100%; height: 300px" />
      </div>
    </div>
    <div class="bottom_wrap">
      <div class="mb20 df_sb">
        <strong class="df_ac"><div class="title_before" />平台短信使用统计</strong>
        <el-date-picker
          v-model="param.selDate"
          type="daterange"
          range-separator=" ~ "
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="initUseStatic"
        />
      </div>
      <div ref="UseStatisticsRef" class="bottom_Ref" style="width: 100%; height: 300px" />
    </div>

    <el-dialog
      title="充值"
      :close-on-click-modal="madelFlag"
      :visible.sync="isShowRecharge"
      width="700px"
    >
      <span class="ml20">商户名称：</span>
      <el-select v-model="payparam.shopId" filterable>
        <el-option
          v-for="item in shopList"
          :key="item.shopId"
          :value="item.shopId"
          :label="item.shopName"
        />
      </el-select>
      <div class="uni_price">
        <div
          v-for="item in mealList"
          :key="item.id"
          class="item"
          :class="{ active: activeMeal.id === item.id }"
          @click="mealChange(item)"
        >
          <div class="p1">
            <strong>{{ item.smsCount }}条</strong>
          </div>
          <div class="placeholder fs12">约{{ item.avePrice }}元/条</div>
          <div class="primaryColor fs12">{{ item.price }}元</div>
        </div>
      </div>
      <div v-if="activeMeal.id" class="ml20 mt20">
        <div>支付方式</div>
        <div class="payMethods">
          <div
            v-for="(item, index) in payMethods"
            :key="index"
            class="item"
            :class="{ active: activePayMethod.code === item.code }"
            @click="payMethodsClick(item)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowRecharge = false">取 消</el-button>
        <el-button :loading="rechargeLoading" type="primary" @click="subRecharge">充 值</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="订单结算"
      :close-on-click-modal="madelFlag"
      :visible.sync="isShowOrder"
      width="600px"
    >
      <div class="order_wrap" style="text-align: center">
        <div class="fs12">扫一扫付款(元)</div>
        <div class="red mt10" style="font-size: 18px">
          <strong>{{ activeMeal.price }}</strong>
        </div>
        <div
          style="border: 1px solid #e4e4e4; border-radius: 4px; padding: 4px"
        >
          <img
            :src="payparam.orderImg"
            style="width: 200px;height200px;"
            alt=""
          >
          <div>打开手机微信</div>
          <div>扫一扫继续付款</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowOrder = false">取消支付</el-button>
        <el-button
          type="primary"
          @click="queryRechargeStatus"
        >已支付</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { smsStaticCase, smsUseStatic, smsStaticWarning, shopSysList, SysMealList, smsRecharge, sysPayMethods, smsQueryRechargeStatus } from '@/api'
import dayjs from 'dayjs'
export default {
  data() {
    return {
      param: {
        selDate: [],
        percent: '0.90'
      },
      madelFlag: this.$store.getters.dialog,
      payparam: {},
      isShowRecharge: false,
      isShowOrder: false,
      useCase: {
        percentage: 0
      },

      rechargeLoading: false,
      shopList: [],
      mealList: [],
      payMethods: [],
      activePayMethod: {},
      activeMeal: {},
      warningOptions: [
        { value: '0.90', label: '90%' },
        { value: '0.80', label: '80%' },
        { value: '0.70', label: '70%' }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '近7天',
          onClick(picker) {
            const date = new Date()
            const end = new Date(date.setDate(date.getDate() - 1))
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 6)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近30天',
          onClick(picker) {
            const date = new Date()
            const end = new Date(date.setDate(date.getDate() - 1))
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 29)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近60天',
          onClick(picker) {
            const date = new Date()
            const end = new Date(date.setDate(date.getDate() - 1))
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近90天',
          onClick(picker) {
            const date = new Date()
            const end = new Date(date.setDate(date.getDate() - 1))
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 89)
            picker.$emit('pick', [start, end])
          }
        }],
        disabledDate(time) {
          var curDate = new Date(new Date().toLocaleDateString()).getTime()
          var preDate = new Date(curDate - 1)
          return time.getTime() > preDate
        }
      }
    }
  },
  mounted() {
    const date = dayjs(new Date()).subtract(1, 'day').format('YYYY-MM-DD')
    const endTime = date
    const startTime = dayjs(date).subtract(6, 'day').format('YYYY-MM-DD')
    this.param.selDate = [startTime, endTime]
    this.initData()
  },
  methods: {
    openRecharge() {
      // this.$set
      this.payparam = {}
      this.isShowRecharge = true
    },
    initData() {
      this.getShops()
      smsStaticCase({ param: {}}).then(res => {
        this.useCase = { ...res.record }
        const percentage = (this.useCase.balance / this.useCase.sum) * 100
        this.$set(this.useCase, 'percentage', Number(percentage.toFixed(2)))
      })
      sysPayMethods({ param: {}}).then(res => {
        this.payMethods = res.recordList
        if (this.payMethods.length > 0) {
          this.activePayMethod = this.payMethods[0]
        }
      })
      this.initUseStatic()
      this.initStaticWarning()
    },
    initUseStatic() {
      smsUseStatic({ param: { startDate: this.param.selDate[0], endDate: this.param.selDate[1] }}).then(res => {
        this.initUseStatistics(res.recordList)
      })
    },
    initStaticWarning() {
      smsStaticWarning({ param: { percent: this.param.percent }}).then(res => {
        this.initSMSType(res.recordList)
      })
    },
    queryRechargeStatus() {
      smsQueryRechargeStatus({ param: { orderId: this.payparam.orderId }}).then(res => {
        if (res.record === '3') {
          this.isShowOrder = false
        } else {
          const map = {
            '0': '待支付',
            '1': '超时未支付',
            '2': '取消支付'
          }
          this.$message.warning(map[res.record])
        }
      })
    },
    subRecharge() {
      const { payparam, activeMeal, activePayMethod } = this
      if (!payparam.shopId) return this.$message.warning('请先选择商户')
      if (!this.activeMeal.id) return this.$message.warning('请先选择充值套餐')
      this.rechargeLoading = true
      smsRecharge({
        param: {
          mealId: activeMeal.id,
          payMethod: activePayMethod.code,
          shopId: payparam.shopId
        }
      }).then(res => {
        this.rechargeLoading = false
        if (res.errorCode !== '000000') return
        this.isShowRecharge = false
        if (res.record.ewm) {
          this.isShowOrder = true
          this.$set(this.payparam, 'orderImg', res.record.ewm)
          this.$set(this.payparam, 'orderId', res.record.orderId)
          return
        }
        this.$set(this.payparam, 'orderId', res.record.orderId)
        this.$message.success('充值成功')
      }, () => {
        this.rechargeLoading = false
      })
    },
    initSMSType(config) {
      const chartDom = echarts.init(this.$refs.SMSTypeRef)
      // var myChart = echarts.init(chartDom, 'dark')
      var option
      option = {
        xAxis: {
          type: 'category',
          data: config.map(i => i.shopName)
        },
        color: ['#72d6ae', '#d2f3e8', '#5fc396', '#e2ae44', '#ea954b'],
        grid: {
          left: '36px',
          right: '10px',
          bottom: '36px'
        },
        yAxis: {
          type: 'value',
          name: '短信数(条)',
          minInterval: 1,
          max: function(value) {
            return (value.max + 10) - value.max % 10
          }
        },
        tooltip: {
          position: function(point, params, dom, rect, size) {
            // 固定在顶部
            return [point[0] - 54, 'top']
          },
          trigger: 'axis',
          formatter: function(arg) {
            // console.log('arg', arg)
            const proportion = (arg[0].data.value / (arg[0].data.value + arg[1].data.value) * 100).toFixed(0)
            const color = proportion > 90 ? '#db7d31' : proportion > 90 ? '#e09e3f' : '#333'
            const res = `
              <span style="color: ${color}">
                已用${arg[0].data.value}条 | ${proportion}%
              </span>
            `

            return res
          }
        },
        series: [
          {
            // data: [9],
            name: '已用',
            data: config.map(i => i.usedCount),
            type: 'bar',
            barWidth: 20,
            stack: 'Search Engine'
          },
          {
            // data: [3],
            data: config.map(i => i.sumCount - i.usedCount),
            name: '剩余',
            type: 'bar',
            barWidth: 20,
            stack: 'Search Engine'
          }
        ]
      }
      const stackInfo = {}
      for (let i = 0; i < option.series[0].data.length; ++i) {
        for (let j = 0; j < option.series.length; ++j) {
          const stackName = option.series[j].stack
          if (!stackName) {
            continue
          }
          if (!stackInfo[stackName]) {
            stackInfo[stackName] = {
              stackStart: [],
              stackEnd: []
            }
          }
          const info = stackInfo[stackName]
          const data = option.series[j].data[i]
          if (data) {
            if (info.stackStart[i] == null) {
              info.stackStart[i] = j
            }
            info.stackEnd[i] = j
          }
        }
      }
      for (let i = 0; i < option.series.length; ++i) {
        const data = option.series[i].data
        const info = stackInfo[option.series[i].stack]
        for (let j = 0; j < option.series[i].data.length; ++j) {
          const isEnd = info.stackEnd[j] === i
          const topBorder = isEnd ? 10 : 0
          const bottomBorder = 0
          data[j] = {
            value: data[j],
            itemStyle: {
              borderRadius: [topBorder, topBorder, bottomBorder, bottomBorder]
            }
          }
        }
      }
      window.addEventListener('resize', () => {
        chartDom.resize()
      })
      option && chartDom.setOption(option)
    },
    initUseStatistics(config) {
      const chartDom = echarts.init(this.$refs.UseStatisticsRef)
      var option
      option = {
        xAxis: {
          type: 'category',
          data: config.map((i) => i.sendDate.slice(5, 10) + '  ' + i.weekDay)
        },
        grid: {
          left: '30px',
          right: '10px',
          bottom: '36px'
        },
        tooltip: {
          trigger: 'item',
          formatter: (param) => {
            const { name, value } = param
            // const weekMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
            // const day = new Date(name).getDay()
            const res = `
              <div class="fs12" style="text-align: center;">${name}</div>
              <div class="fs12 df_ac">
                <div style="width: 8px;height: 8px;border-radius: 50%;background-color: #6ed3a6;"></div>
                <div class="ml10">短信数：${value}条</div>
              </div>
            `
            console.log('param', param)
            return res
          },
          position: function(point, params, dom, rect, size) {
            // 固定在顶部
            return [point[0] - 60, point[1] - 92]
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1,
          max: function(value) {
            return (value.max + 10) - value.max % 10
          }
          // name: '短信数(条)'
        },
        series: [
          {
            data: config.map((i) => i.sendCount),
            type: 'line',
            smooth: true,
            itemStyle: {
              normal: {
                color: '#77dab1'
              }
            },
            lineStyle: {
              color: '#77dab1',
              width: '2'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                1,
                [
                  {
                    offset: 0,
                    color: '#71d8ad'
                    // 渐变色的开始颜色
                  },
                  {
                    offset: 1,
                    color: '#fcfefd'
                    // 渐变色的开始颜色
                  }
                ],
                false
              )
            }
          }
        ]
      }
      window.addEventListener('resize', () => {
        chartDom.resize()
      })
      option && chartDom.setOption(option)
    },
    payMethodsClick(row) {
      this.activePayMethod = { ...row }
    },
    mealChange(val) {
      this.activeMeal = { ...val }
    },
    // 获取商户
    getShops() {
      shopSysList({
        param: { status: '1' }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        this.shopList = res.recordList
      })
      SysMealList({ param: { status: '0' }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.mealList = res.recordList.map(item => {
          item.avePrice = (item.price / item.smsCount).toFixed(2)
          return item
        })
        if (this.mealList.length > 0) {
          this.activeMeal = this.mealList[0]
        }
      })
    }

  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/variables.scss';
.uni_price {
  display: flex;
  flex-wrap: wrap;
  .item {
    padding: 24px 60px;
    margin: 12px 12px;
    cursor: pointer;
    border: 1px solid #e9ebf6;
    border-radius: 8px;
    text-align: center;
    .placeholder {
      margin: 6px 0;
    }
  }
  .active{
    background-color: #e9ebf6;
    border: 1px solid #495db9;
  }
}
.payMethods{
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  .item{
    cursor: pointer;
    padding: 6px 20px;
    border-radius: 5px;
    margin-right: 20px;
    border: 1px solid #e9ebf6;
  }
  .active{
    background-color: #e9ebf6;
    border: 1px solid #495db9;
  }
}
.separate {
  display: flex;
  width: 2px;
  height: 100%;
  background-color: #e4e4e4;
  margin: 0 10px;
}
.top_right{
  flex: 6;
  border-radius: 4px;
  border: 1px solid #EEEEEE;
  padding: 12px 20px 0;
  .header {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.bottom_wrap{
  margin-top: 20px;
  border-radius: 4px;
  border: 1px solid #EEEEEE;
  padding: 12px 20px 0;
  .header {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  /* .bottom_Ref{
    transform: scale(1.16);
  } */
}
.top_left {
  flex: 4;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-radius: 4px;
  border: 1px solid #EEEEEE;
  padding: 12px 20px 0;
  position: relative;
  .progress_wrap{
    position: absolute;
    text-align: center;
    top: 150px;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .header {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .text_wrap{
    width: 390px;
    margin-top: 20px;
    text-align: center;
    display: flex;
    .item{
      text-align: center;
      flex: 1;
    }
  }
}
.progress {
  margin: 20px auto;
}
.title_before{
  width: 3px;
  height: 16px;
  background: $primaryColor;
  border-radius: 2px;
  margin-right: 10px;
}
</style>
